<template>
  <view class="uni-container">
    <uni-forms ref="form" :model="formData" validateTrigger="bind" label-width="120px">
         <uni-forms-item name="parent_id" label="上级" v-if="formData.parent_id">
    		<uni-data-select
    			 collection="mydb-department"
    			 field="_id as value, name as text"
    			 v-model="formData.parent_id"
           :disabled="true"
    		 />
    </uni-forms-item>
      <uni-forms-item name="name" label="部门名称" required>
        <uni-easyinput v-model="formData.name"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="description" label="部门描述">
        <uni-easyinput v-model="formData.description"></uni-easyinput>
      </uni-forms-item>
     <uni-forms-item name="owner" label="部门负责人">
        <uni-data-select collection="uni-id-users" field="_id as value, nickname as text" v-model="formData.owner"
          :multiple="true" />
      </uni-forms-item>
      <uni-forms-item name="members" label="部门成员">
        <uni-data-select collection="uni-id-users" field="_id as value, nickname as text" v-model="formData.members"
          :multiple="true" />
      </uni-forms-item>
	  <uni-forms-item name="created_at" label="创建时间">
	    <uni-datetime-picker return-type="timestamp" v-model="formData.created_at" disabled></uni-datetime-picker>
	  </uni-forms-item>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <navigator open-type="navigateBack" style="margin-left: 15px;">
          <button class="uni-button" style="width: 100px;">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import { validator } from '../../js_sdk/validator/mydb-department.js';

  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'mydb-department';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

  

  export default {
    data() {
      let formData = {
        "name": "",
        "type": "department",
        "parent_id": "",
        "owner": [],
        "members": [],
        "description": ""
      }
      return {
        formData,
       formOptions: {
         "type_localdata": [
           {
             "value": "department",
             "text": "部门"
           },
           {
             "value": "team",
             "text": "团队"
           },
           {
             "value": "store",
             "text": "门店"
           },
           {
             "value": "employee",
             "text": "员工"
           }
         ]
        },
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
    onLoad(e) {
      if (e.id) {
        const id = e.id
        this.formDataId = id
        this.getDetail(id)
      }
      if (e.parent_id) {
        this.formData.parent_id = options.parent_id
      }
	  switch (e.type){
	  	case 'department':
	  		this.formData.type='team'
	  		break;
	  	case 'team':
	  		this.formData.type='store'
	  		break;
	  	default:
	  		this.formData.type='department'
	  		break;
	  }
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      
      /**
       * 验证表单并提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.validate().then((res) => {
          return this.submitForm(res)
        }).catch(() => {
        }).finally(() => {
          uni.hideLoading()
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
		  value.type=this.formData.type
		  value.update_date=new Date().getTime()
        return db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
          uni.showToast({
            title: '修改成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      },

      /**
       * 获取表单数据
       * @param {Object} id
       */
      getDetail(id) {
        uni.showLoading({
          mask: true
        })
        db.collection(dbCollectionName).doc(id).get().then((res) => {
          const data = res.result.data[0]
          if (data) {
            this.formData = data
            
          }
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        }).finally(() => {
          uni.hideLoading()
        })
      }
    }
  }
</script>
